[Golang] gorm 2.0 insert on duplicate update


Posted by kitecloud213 on 2020-09-09

最近升級了 gorm 2.0,紀錄一下 on duplicate update 寫法

type TableItem struct {
    ID int // PK
    Amount int
}

func Create(ID int, amount int) error {
    db := dbPool.Get() // 取得已經建立好的 connection
    item := &TableItem{
        ID: ID,
        Amount: amount,
    }
    err := db.Clauses(clause.OnConflict{
        DoUpdates: clause.Assignments(map[string]interface{}{"amount": item.Amount}),
    }).Create(item).Error
    if err != nil {
        return err
    }

    return nil
}

#golang #gorm







Related Posts

Vite系列#安裝vite&在 Composition API 及 Options API 進行切換

Vite系列#安裝vite&在 Composition API 及 Options API 進行切換

React(11) - class & function component 比較 & useRef

React(11) - class & function component 比較 & useRef

The introduction and difference between class component and function component in React

The introduction and difference between class component and function component in React


Comments